// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

/**
 * 依据筛选条件查询公告信息
 */
exports.main = async (event, context) => {
  const { type, region, classes, sort, startTime, endTime, skip, limit, total } = event
  const params = { type }

  // 地区
  if (Array.isArray(region)) {
    region.forEach((v, i) => {
      params[`region.${i}`] = v
    })
  }

  // 类别
  if (Array.isArray(classes)) {
    classes.forEach((v, i) => {
      params[`classes.${i}`] = v
    })
  }

  // 时间
  if (startTime && endTime) {
    params.time = _.and(_.gte(new Date(startTime)), _.lte(new Date(endTime)))
  } else if (startTime) {
    params.time = _.gte(new Date(startTime))
  } else if (endTime) {
    params.time = _.lte(new Date(endTime))
  }

  // 排序条件
  const conditions = {}
  if (sort === 'time') {
    conditions.time = -1
  }
  conditions.update = -1

  const res = await db.collection('notice')
    .aggregate()
    .match(params)
    .sort(conditions)
    .skip(skip)
    .limit(limit)
    .end()
  
  // 获取符合条件的公告总记录数
  if (!total) {
    const countRes = await db.collection('notice')
      .aggregate()
      .match(params)
      .count('total')
      .end()
    res.total = countRes.list[0] ? countRes.list[0].total : 0
  } else {
    res.total = total
  }

  return res
}